// This file is part of OpenTSDB.
// Copyright (C) 2017 TeleDB Development Group.
//
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 2.1 of the License, or (at your
// option) any later version.  This program is distributed in the hope that it
// will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser
// General Public License for more details.  You should have received a copy
// of the GNU Lesser General Public License along with this program.  If not,
// see <http://www.gnu.org/licenses/>.
package net.opentsdb.tools.http;

import net.opentsdb.bean.MetaBean;
import net.opentsdb.utils.JSON;

import org.apache.http.HttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class SendClient implements AutoCloseable{

    private static final Logger LOG = LoggerFactory.getLogger(SendClient.class);

    private final HttpSender httpSender;
    private final TSDBConfig tsdbConfig;

    public SendClient(String url){

        tsdbConfig = TSDBConfig.builder(url).build();
        httpSender = HttpClientFactory.createHttpClient(tsdbConfig);

        this.httpSender.start();
    }

    public void sendMeta(byte[] tsuid, String metric, Map<String,String> tags){
        MetaBean bean = new MetaBean();
        bean.setTsuId(tsuid);
        bean.setMetric(metric);
        bean.setTags(tags);

        List<MetaBean> list = new ArrayList<>();
        list.add(bean);
        String json = JSON.serializeToString(list);
        this.asyncSendJson(json);
    }

    public void sendObject(Object obj){
        String json = JSON.serializeToString(obj);
        this.asyncSendJson(json);
    }

    public HttpResponse sendGetRequest(String url) {
        return this.httpSender.sendGetRequest(url);
    }

    public void sendJSON(String json){
        this.asyncSendJson(json);
    }

    public void asyncSendJson(String json){
        this.httpSender.postJson(tsdbConfig.getUrl(),json);
    }

    @Override
    public void close() throws Exception {
        this.httpSender.close();
    }
}
